<template>
  <div class="components-container feature-out">
    <div ref="searchDiv">
      <div class="filter-container">
        <el-date-picker
          v-model="datePicker"
          ref="pick"
          size="small"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="filter-item"
        >
        </el-date-picker>
        <el-select
          size="small"
          v-model="listQuery.dataSource"
          clearable
          placeholder="请选择数据源"
          class="filter-item"
          style="width: 200px;"
        >
          <el-option
            v-for="item in source_name"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>

        <el-button
          size="small"
          @click="handleFilter"
          type="primary"
          class="filter-item"
          ref="btnQuery"
          >查询</el-button
        >
        <el-button
          @click="handleReset"
          size="small"
          type="primary"
          class="filter-item"
          ref="btnRefresh"
          >重置</el-button
        >
        <el-button
          @click="downloand"
          size="small"
          type="primary"
          class="filter-item"
          ref="btnRefresh"
          >下载</el-button
        >
      </div>
      <el-alert
        :title="
          '总调用次数:' +
            totalTitle.total +
            ' 查询成功次数:' +
            totalTitle.queryTotal +
            ' 查得成功次数:' +
            totalTitle.sucTotal +
            ' 调用失败次数:' +
            totalTitle.failTotal +
            ' 查询成功率:' +
            totalTitle.queryRate +
            ' 查得成功率:' +
            totalTitle.sucRate
        "
        :closable="false"
        type="info"
        style="margin-bottom: 20px;"
      >
      </el-alert>
    </div>
    <el-table
      :data="tableData"
      :max-height="tableHeight"
      style="width: 100%;margin-bottom: 12px;"
    >
      <!-- <el-table-column
        label="时间"
        prop="date"
        align="center"
        min-width="160px"
      ></el-table-column> -->
      <el-table-column
        label="数据源"
        prop="dataSource"
        align="center"
        min-width="120px"
      ></el-table-column>
      <el-table-column
        label="接口名称"
        prop="interfaceName"
        align="center"
        min-width="200px"
      ></el-table-column>
      <el-table-column
        label="接口地址"
        prop="url"
        align="center"
        min-width="320px"
      ></el-table-column>
      <!-- <el-table-column
        label="调用方式"
        prop="callType"
        align="center"
      ></el-table-column> -->
      <el-table-column
        label="调用次数"
        prop="callCount"
        align="center"
        min-width="120px"
      ></el-table-column>
      <el-table-column
        label="查询成功次数"
        prop="callQuery"
        align="center"
        min-width="160px"
      ></el-table-column>
      <el-table-column
        label="查得成功次数"
        prop="callSuc"
        align="center"
        min-width="160px"
      ></el-table-column>
      <el-table-column
        label="调用失败次数"
        prop="callFail"
        align="center"
        min-width="120px"
      ></el-table-column>
      <el-table-column
        label="查询成功率"
        prop="callQueryRate"
        align="center"
        min-width="160px"
      >
        <template slot-scope="scope">
          {{
            scope.row.callQueryRate !== null
              ? (scope.row.callQueryRate * 100).toFixed(2) + '%'
              : '-'
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="查得成功率"
        prop="callSucRate"
        align="center"
        min-width="120px"
      >
        <template slot-scope="scope">
          {{
            scope.row.callSucRate !== null
              ? (scope.row.callSucRate * 100).toFixed(2) + '%'
              : '-'
          }}
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch, Prop } from 'vue-property-decorator'
import { parseTimeJS as parseTime } from '@/utils' // 时间控件
import {
  getNameMap,
  listDownload,
  getList,
  downloadUrl
} from '@/api/risksystem/dataGateway/interface.ts'
import { Message } from 'element-ui'

const defaultQuery = {}
@Component({
  name: 'trustTrial',
  components: {
    //引用的组件在这里声明
  }
})
export default class extends Vue {
  // 文件下载
  private startDate = new Date().setTime(
    new Date().getTime() - 3600 * 1000 * 24 * 30
  )
  private endDate = new Date().setTime(new Date().getTime() - 3600 * 1000 * 24)
  private tableData = []
  private tableHeight: any = null
  private source_name = []
  private totalTitle: any = {
    failTotal: 0,
    queryRate: 0,
    queryTotal: 0,
    sucRate: 0,
    sucTotal: 0,
    total: 0
  }

  private total = 0
  private datePicker: any = [
    this.formatDate(new Date(this.startDate)),
    this.formatDate(new Date(this.endDate))
  ]
  private listQuery: any = {
    currentPage: 1,
    dataSource: '',
    limit: 10,
    startDate: this.datePicker[0],
    endDate: this.datePicker[1]
  }
  created() {
    this.getList()
    this.getNameMap()
  }
  mounted() {
    this.init()
    // this.getApply()
  }
  @Watch('datePicker')
  private onDatePickerChange(value: boolean) {
    this.listQuery.startDate = this.datePicker ? this.datePicker[0] : undefined
    this.listQuery.endDate = this.datePicker ? this.datePicker[1] : undefined
  }
  beforeDestroy() {
    // 摧毁监听事件
    window.onresize = null
  }
  // 表格高度
  private init() {
    var _this = this
    this.$nextTick(() => {
      this.tableHeight =
        window.innerHeight - (this.$refs.searchDiv as any).offsetHeight - 250
    })
    window.onresize = () => {
      this.$nextTick(() => {
        this.tableHeight =
          window.innerHeight - (this.$refs.searchDiv as any).offsetHeight - 250
      })
    }
  }
  private async getNameMap() {
    const { data } = await getNameMap()
    this.source_name = data
  }
  // 列表获取
  private async getList() {
    const { data } = await getList(this.listQuery)
    this.tableData = data.table
    this.totalTitle = data.total
      ? data.total
      : {
          failTotal: 0,
          queryRate: 0,
          queryTotal: 0,
          sucRate: 0,
          sucTotal: 0,
          total: 0
        }
    this.totalTitle.queryRate = data.total
      ? (this.totalTitle.queryRate * 100).toFixed(2) + '%'
      : '--'
    this.totalTitle.sucRate = data.total
      ? (this.totalTitle.sucRate * 100).toFixed(2) + '%'
      : '--'
    this.total = data.dataTotal
  }

  // 查询、重置
  private handleFilter(val: string) {
    // this.listQuery.current_page = 1
    this.getList()
  }
  // 跳转页码查询
  handleCurrentChange(val: any) {
    this.listQuery.page = val
    this.getList()
  }
  // size切换查询
  handleSizeChange(val: any) {
    this.listQuery.limit = val
    this.getList()
  }
  private handleReset(val: string) {
    this.datePicker = [
      this.formatDate(new Date(this.startDate)),
      this.formatDate(new Date(this.endDate))
    ]
    this.listQuery = {
      currentPage: 1,
      dataSource: '',
      limit: 10,
      startDate: this.datePicker[0],
      endDate: this.datePicker[1]
    }
    this.getList()
  }
  // private downloand() {
  //   window.location.href = downloadUrl
  // }
  private async downloand() {
    // console.log(downloadUrl)
    // window.open(encodeURI(downloadUrl))
    // const res = await listDownload(this.listQuery)
    listDownload(this.listQuery).then(data => {
      if (!data) {
        Message({
          message: '文件下载失败',
          type: 'error',
          duration: 5 * 1000
        })
        return
      }
      console.log(typeof window.navigator.msSaveBlob)
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(
          new Blob([data as any]),

          '数据接口使用情况' +
            this.listQuery.startDate +
            '~' +
            this.listQuery.endDate +
            '.xlsx'
        )
        console.log(new Blob([data as any]))
      } else {
        console.log(new Blob([data as any]))
        let url = window.URL.createObjectURL(new Blob([data as any]))
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute(
          'download',
          '数据接口使用情况' +
            this.listQuery.startDate +
            '~' +
            this.listQuery.endDate +
            '.xlsx'
        )
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link) //下载完成移除元素
        window.URL.revokeObjectURL(url) //释放掉blob对象
      }
    })
  }
  private formatDate(now: any) {
    var year = now.getFullYear() //取得4位数的年份
    var month = now.getMonth() + 1 //取得日期中的月份，其中0表示1月，11表示12月
    var date = now.getDate() //返回日期月份中的天数（1到31）
    var hour = now.getHours() //返回日期中的小时数（0到23）
    var minute = now.getMinutes() //返回日期中的分钟数（0到59）
    var second = now.getSeconds() //返回日期中的秒数（0到59）
    return (
      year +
      '-' +
      (month < 10 ? '0' + month : month) +
      '-' +
      (date < 10 ? '0' + date : date)
      // (hour < 10 ? '0' + hour : hour) +
      // ':' +
      // (minute < 10 ? '0' + minute : minute) +
      // ':' +
      // (second < 10 ? '0' + second : second)
    )
  }
}
</script>
<style scoped>
.components-container {
  padding: 20px;
}
</style>
